<!-- 定标结果确认 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
      	fontSize: '14px',
      	color: '#B2B2B2',
      	lineHight: '20px'
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="purchaseBill" required>
          <u--input v-model="model.purchaseBill" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="proposer" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.proposer"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.proposer"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请部门" prop="departId" required>
          <h-select-depart-input
            disabled
            v-model="model.departId"
            :departName="model.proposerDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>
        <u-form-item label="申请时间" prop="createTime" required>
          <u--input v-model="model.createTime" disabled></u--input>
        </u-form-item>

        <!-- <u-form-item label="工期(供货期)" prop="supplyTime" required>
          <h-time-select
            mode="date"
            ref="remittanceDate"
            v-model="model.supplyTime"
            placeholder="请选择工期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item> -->
        <u-form-item label="开标时间" prop="calibrationTime" required>
          <h-time-select
            mode="datetime"
            ref="remittanceDate"
            v-model="model.calibrationTime"
            placeholder="请选择开标时间"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="预算价(元)" prop="budget" required>
					<h-money-input
						placeholder="请输入预算价"
						v-model="model.budget"
						disabled
					></h-money-input>
        </u-form-item>
				<u-form-item label="中标总价(元)" prop="totalBidPrice">
					<h-money-input
						placeholder="请输入中标总价"
						v-model="model.totalBidPrice"
						disabled
					></h-money-input>
				</u-form-item>
        <!-- <u-form-item label="开票方式" prop="invoiceManner" required>
          <u--input placeholder="请输入开票方式" v-model="model.invoiceManner"></u--input>
        </u-form-item> -->
        <u-form-item label="所属团队" prop="teamId" required>
          <h-select-team-input
            style="width: 100%"
            v-model="model.teamId"
            objectField="model.teamId"
            placeholder="请选择所属团队"
            border="surround"
            :tdlx="3"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
            @input="checkSwitch($event)"
          />
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">
					<view>招标采购申请信息</view>
					<view style="color: #f56c6c; font-size: 12px;">注：只可关联一个招标采购申请</view>
				</view>
        <view class="space-y-1 py-1" v-if="!tenderFormData || !tenderFormData.length">
          <u-button size="small" type="primary" @click="handleAddTrendForm">新增</u-button>
        </view>
				<template>
					<TrendFormInfo
						v-for="(item, index) in tenderFormData"
						:key="index"
					  :teamId="model.teamId"
					  :item="item"
					  :index="index"
					  @edit="handleEditTrendForm"
					  @remove="handleRemoveTrendForm"
					  @copy="handleCopyTrendForm"
					></TrendFormInfo>
				</template>
				
        <u-popup mode="bottom" :show="showTrendFormModal" closeable :closeOnClickOverlay="false" :round="10" @close="closeTrendFormModal" @open="openTrendFormModal">
          <TrendForm
            :teamId="model.teamId"
						:dataSource="tenderFormData"
            ref="dataForm"
            :index="index"
            @submit="handleTrendFormSubmit"
            @close="showTrendFormModal = false"
          ></TrendForm>
        </u-popup>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">中标信息</view>
        <view class="space-y-1 py-1" v-if="!isShowBtn">
          <u-button size="small" type="primary" @click="handleAddWinBidForm">新增</u-button>
        </view>
				<template>
					<WinTheBidFormInfo
						:isShowBtn="isShowBtn"
						v-for="(item, index) in winBidFormData"
					 :key="index"
					  :teamId="model.teamId"
					  :item="item"
					  :index="index"
					  @edit="handleEditWinBidForm"
					  @remove="handleRemoveWinBidForm"
					  @copy="handleCopyWinBidForm"
					></WinTheBidFormInfo>
				</template>
        <u-popup mode="bottom" :closeOnClickOverlay="false" :round="10" :show="showWinBidFormModal">
          <WinTheBidForm
            :teamId="model.teamId"
            ref="winBidForm"
            :index="index"
            @submit="handleWinBidFormSubmit"
            @close="closeWinBidFormModal"
          ></WinTheBidForm>
        </u-popup>
      </view>

      <div class="basic-style">
        <u-form-item
          label="各厂家报价、谈判情况描述及选定该厂家供货的原因：（重点描述品牌、价格对比情况、原厂还是代理商等）"
          prop="quoteDescription"
          required
        >
          <!-- #ifdef H5 -->
          <u--textarea
            confirm-type="done"
            :maxlength="5000"
            v-model="model.quoteDescription"
            placeholder="重点描述品牌、价格对比情况、是原厂还是代理商等"
          ></u--textarea>
          <!-- #endif -->
					<!-- #ifndef H5 -->
					<u--textarea
					  :confirm-type="null"
					  :maxlength="5000"
					  v-model="model.quoteDescription"
					  placeholder="重点描述品牌、价格对比情况、是原厂还是代理商等"
					></u--textarea>
					<!-- #endif -->
        </u-form-item>
        <u-form-item label="历史采购情况说明：（重点描述品牌、价格情况）" prop="historyDescription">
					<!-- #ifdef H5 -->
					<u--textarea
					  confirm-type="done"
					  :maxlength="1000"
					  v-model="model.historyDescription"
					  placeholder="重点描述品牌、价格情况"
					></u--textarea>
					<!-- #endif -->
					<!-- #ifndef H5 -->
					<u--textarea
					  :confirm-type="null"
					  :maxlength="1000"
						count
					  v-model="model.historyDescription"
					  placeholder="重点描述品牌、价格情况"
					></u--textarea>
					<!-- #endif -->
        </u-form-item>
        <u-form-item label="与采购申请的差异：（重点描述规格型号、参数及品牌、数量等更改项目）" prop="differenceDescription" required>
					<!-- #ifdef H5 -->
					<u--textarea
					  confirm-type="done"
					  :maxlength="1000"
					  v-model="model.differenceDescription"
					  placeholder="重点描述规格型号、参数及品牌、数量等更改项目"
					></u--textarea>
					<!-- #endif -->
					<!-- #ifndef H5 -->
					<u--textarea
					  :confirm-type="null"
					  :maxlength="1000"
						count
					  v-model="model.differenceDescription"
					  placeholder="重点描述规格型号、参数及品牌、数量等更改项目"
					></u--textarea>
					<!-- #endif -->
        </u-form-item>
        <u-form-item label="申购单位意见：（对产品品牌、价格、数量的认可及增减等描述）" prop="opinionDescription" required>
					<!-- #ifdef H5 -->
					<u--textarea
					  confirm-type="done"
					  :maxlength="1000"
					  v-model="model.opinionDescription"
					  placeholder="对产品品牌、价格、数量的认可及增减等描述"
					></u--textarea>
					<!-- #endif -->
					<!-- #ifndef H5 -->
					<u--textarea
					  :confirm-type="null"
					  :maxlength="1000"
						count
					  v-model="model.opinionDescription"
					  placeholder="对产品品牌、价格、数量的认可及增减等描述"
					></u--textarea>
					<!-- #endif -->
        </u-form-item>
        <u-form-item label="备注" prop="remark">
          
					
					<!-- #ifdef H5 -->
					<u--textarea confirm-type="done" :maxlength="500" v-model="model.remark" placeholder="请输入备注"></u--textarea>
					<!-- #endif -->
					<!-- #ifndef H5 -->
					<u--textarea :confirm-type="null" :maxlength="500" count v-model="model.remark" placeholder="请输入备注"></u--textarea>
					<!-- #endif -->
        </u-form-item>
      </div>

      <view class="basic-style">
        <view class="basic-title basic-border">附件信息（1、询比价对比表；2、中标厂家盖章报价单；3、其它）</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.purchaseFile" :isIcon="false"></h-upload-file>
          <file-list v-if="model.purchaseFile" v-model="model.purchaseFile" :isDelete="true"></file-list>
        </view>
      </view>
			
			<view class="space-x-1 px-1 btn_position">
				<u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDraft"></u-button>
				<u-button :disabled="isSubmit"  type="primary"  text="保存并提交" @click="onSubmit"></u-button>
			</view>
			<view style="height: 100rpx;"></view>
    </u-form>

    <u-modal
      :show="confirmTenderModal"
      title="是否确认"
      :closeOnClickOverlay="true"
      :asyncClose="true"
      @cancel="handleSwitchCancel"
      @confirm="handleSwitchConfirm"
      showCancelButton
    >
      <view class="slot-content">
        <view>是否确认切换采购大类，此操作将会清空物料明细中已填写的所有信息？</view>
      </view>
    </u-modal>
		
		<u-toast ref="uToast"></u-toast>
		<ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { gainBillNo, add, info, edit } from '@/api/purchase/ErpPurchaseCalibrationForm'
import { queryByIdPurchaseCalibrationDetailAllList, queryByIdPurchaseCalibrationUnitAllList, erpPurchaseApplyInvitationQueryById } from '@/api/index.js'
import http from '@/utils/request'
import fileList from '@/pages/synergy/components/fileList.vue'
import TrendForm from './components/TenderForm.vue'
import TrendFormInfo from './components/TenderFormInfo.vue'
import WinTheBidForm from './components/WinTheBidForm.vue'
import WinTheBidFormInfo from './components/WinTheBidFormInfo.vue'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
import Decimal from 'decimal.js'
export default {
  name: 'ErpPurchaseCalibrationForm',
  components: {
    fileList,
    TrendForm,
    TrendFormInfo,
    WinTheBidForm,
    WinTheBidFormInfo,
		ProcessNodeConfiguration
  },
  data() {
    return {
			isShowBtn: false, // 是否展示中标信息的按钮
			backUpTeamId: '', // 所属团队初始值
			isSubmit: false,
			showAdd: false, // 投标采购申请只能有一条数据
      index: null,
      showTrendFormModal: false,
      confirmTenderModal: false,
      showWinBidFormModal: false,
      loading: false,
      id: '',
      basicForm: {},
      tenderFormData: [],
      winBidFormData: [],
      model: {
        // 基本信息 - 公用
        bpmBizTitle: '',
        purchaseBill: '',
        proposer: '',
        departId: '',
        createTime: '',
        calibrationTime: '',
        budget: '',
        teamId: '',
      },
      rules: {
				purchaseBill: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
				departId: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
				proposer: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
				createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
				
        // supplyTime: [{ required: true, message: '请选择工期(供货期)!', trigger: ['change', 'blur'] }],
        calibrationTime: [{ required: true, message: '请选择开标时间!', trigger: ['change', 'blur'] }],
        budget: [
          { required: true, message: '请输入预算价!', trigger: ['change', 'blur'] },
          { pattern: /^([0-9]*[1-9][0-9]*(\.[0-9]+)?|[0]+\.[0-9]*[1-9][0-9]*)$/, message: '请输入大于0的数字!' },
        ],
        // invoiceManner: [{ required: true, message: '请选择开票方式!', trigger: ['change', 'blur'] }],
        quoteDescription: [{ required: true, message: '请输入描述!', trigger: ['change', 'blur'] }],
        differenceDescription: [{ required: true, message: '请输入描述', trigger: ['change', 'blur'] }],
        opinionDescription: [{ required: true, message: '请输入描述', trigger: ['change', 'blur'] }],
        teamId: [{ required: true, message: '请选择所属团队!', trigger: ['change', 'blur'] }],
      },
			
			//代码生成后需手动设置流程编码
			flowCode: 'onl_erp_purchase_calibration',
			formUrl: "/erp/purchase/procurement/modules/ErpPurchaseCalibrationForm",
			formUrlMobile: "/pages/synergy/erpPurchaseCalibrationList",
			beanName: 'erpPurchaseCalibrationServiceImpl',
			processId: '1538773238404935682',
			provisionBroadList: [], // 获取采购类型
    }
  },
  onLoad({ id }) {
    this.id = id || ''
		this.getProvisionBroadList()
  },
  created() {
    if (this.id) {
      this.initInfo()
			this.getapplyAllList()
			this.getapplyAllListUnit()
    } else {
      this.initForm()
      this.initBillNo()
    }
    // this.initBuyerInfo()
  },
  computed: {
    ...mapState(['userInfo']),
  },
  methods: {
		// 获取招标哦采购申请详情
		async getPurchasing (id) {
			const response = await erpPurchaseApplyInvitationQueryById({ id })
			const data = response?.result || {}
			 this.$set(this.model, 'budget', data.projectBudget || 0)
		},
    /**
     * 修改值时，检查是否需要弹出对话框确认修改
     * 取消 modal 的时候，需要将值还原
     * @param {String} key BasicForm 中的key值
     * @param {Function} fn 回调函数
     * @param {any} data 回调函数参数
     */
    checkSwitch(data) {
      this.$nextTick(() => {
        const oldData = this.backUpTeamId
        if (oldData && oldData !== this.model.teamId && this.tenderFormData && this.tenderFormData.length) {
          this.confirmTenderModal = true
          this.resetKey = `backUpTeamId`
        } else {
					this.backUpTeamId = this.model.teamId
				}
      })
    },
    /**
     * 弹窗点击确认
     */
    handleSwitchConfirm() {
      this.tenderFormData = []
      this.confirmTenderModal = false
			if (this.isShowBtn) {
				this.isShowBtn = false
				this.winBidFormData = []
				this.onTotalBidding(this.winBidFormData) // 计算总价
			}
    },
    /**
     * 弹窗点击取消
     */
    handleSwitchCancel() {
      // 还原修改的数据
      if (this.resetKey) {
        let realKey = this.resetKey.replace('backUp', '')
        realKey = realKey[0].toLowerCase() + realKey.slice(1)
        this.isReset = true
        this.$set(this.model, realKey, this[this.resetKey])
        setTimeout(() => (this.isReset = false), 0)
      }
      this.confirmTenderModal = false
    },
    handleAddTrendForm() {
      if (!this.model.teamId) {
        this.$u.toast('请先选择所属团队')
        return false
      }
      this.index = null
      this.showTrendFormModal = true
    },
    handleCopyTrendForm([item, index]) {
      this.tenderFormData.push({
        ...item,
      })
      this.$u.toast('复制成功')
			this.handleShowBidBtn()
    },
    handleEditTrendForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showTrendFormModal = true
    },
    handleRemoveTrendForm(item) {
      this.tenderFormData = this.tenderFormData.filter((i) => i !== item)
			if (!this.tenderFormData || !this.tenderFormData.length) {
				this.winBidFormData = []
				this.$nextTick(() => {
					this.closeWinBidFormModal()
					this.onTotalBidding(this.winBidFormData) // 计算总价
				})
			}
			this.handleShowBidBtn()
    },
    closeTrendFormModal() {
      this.$refs.dataForm.reset()
      this.basicForm = {}
      this.index = null
			this.showTrendFormModal = false
    },
    openTrendFormModal() {
      this.$refs.dataForm.basicForm = this.basicForm
    },
    /**
     * 子表单新增点击确认
     */
    handleTrendFormSubmit([data, index]) {
      this.showTrendFormModal = false
      if (typeof index === 'number') {
				if (index == 0 && this.tenderFormData[0].projectId != data.projectId) {
					this.tenderFormData = [data]
				} else {
					this.$set(this.tenderFormData, index, data)
				}
      } else {
        this.tenderFormData.push(data)
      }
      // this.initBuyerInfo()
			// 判断中标信息按钮是否隐藏
			this.handleShowBidBtn()
			// 获取中标信息
			if (this.tenderFormData && this.tenderFormData.length) {
				if (this.tenderFormData[0].opinionId) {
					// 当有值的时候则获取中标信息数据
					let params = {
						column: 'createTime',
						order: 'desc',
						pageNo: 1,
						pageSize: 100,
						billId: this.tenderFormData[0].opinionId
					}
					http.get('/api/erp/purchase/procurement/erpPurchaseCalibrationOptionUnit/allList', params).then(res => {
						if (res.success) {
							this.winBidFormData = res.result.records
							this.handleShowBidBtn()
							this.$nextTick(() => {
								this.closeWinBidFormModal()
								this.onTotalBidding(this.winBidFormData) // 计算总价
							})
						} else {
							this.handleShowBidBtn()
							this.winBidFormData = []
							this.$nextTick(() => {
								this.closeWinBidFormModal()
								this.onTotalBidding(this.winBidFormData) // 计算总价
							})
						}
					}).catch(err => {
						this.handleShowBidBtn()
						this.winBidFormData = []
						this.$nextTick(() => {
							this.closeWinBidFormModal()
							this.onTotalBidding(this.winBidFormData) // 计算总价
						})
					})
				} else {
					// 没有值清空中标信息里面的数据
					this.handleShowBidBtn()
					this.winBidFormData = []
					this.$nextTick(() => {
						this.closeWinBidFormModal()
						this.onTotalBidding(this.winBidFormData) // 计算总价
					})
				}
			}
    },
    handleAddWinBidForm() {
      this.index = null
      this.showWinBidFormModal = true
    },
    handleCopyWinBidForm([item, index]) {
      this.winBidFormData.push({
        ...item,
      })
      this.$u.toast('复制成功')
			this.onTotalBidding(this.winBidFormData) // 计算总价
    },
    handleEditWinBidForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showWinBidFormModal = true
			this.$nextTick(() => {
				this.$refs.winBidForm.basicForm = {...this.basicForm}
			})
    },
    handleRemoveWinBidForm(item) {
      this.winBidFormData = this.winBidFormData.filter((i) => i !== item)
			this.onTotalBidding(this.winBidFormData) // 计算总价
    },
    closeWinBidFormModal() {
      this.$refs.winBidForm?.reset()
      this.basicForm = {}
      this.index = null
			this.showWinBidFormModal = false
    },
    /**
     * 子表单新增点击确认
     */
    handleWinBidFormSubmit([data, index]) {
      // this.showWinBidFormModal = false
      if (typeof index === 'number') {
        this.$set(this.winBidFormData, index, data)
      } else {
        this.winBidFormData.push(data)
      }
			this.$nextTick(() => {
				this.closeWinBidFormModal()
				this.onTotalBidding(this.winBidFormData) // 计算总价
			})
    },
		onTotalBidding (arr) {
			if (arr && arr.length) {
				let totalBidPrice = 0
				arr.forEach(item => {
					totalBidPrice += Number(item.bidding)
				})
				this.$set(this.model, 'totalBidPrice', totalBidPrice)
			} else {
				this.$set(this.model, 'totalBidPrice', '0')
			}
		},
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo()
      this.model.purchaseBill = res.result
      this.model.bpmBizTitle = this.userInfo?.employee?.name + '-' + this.model.purchaseBill //标题
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.proposer = this.userInfo.empId //当前登录人
      this.model.departId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    },
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
      this.model = Object.assign({}, data)
			this.backUpTeamId = data.teamId
			this.editCount = 0
    },
		// 招标采购申请信息
		async getapplyAllList () {
			var params = await {
				column: 'createTime',
				order: 'desc',
				pageNo: 1,
				pageSize: 100,
				billId: this.id
			}
			queryByIdPurchaseCalibrationDetailAllList(params).then(async res => {
				if(res.success){
					this.tenderFormData = res.result || []
					// 获取招标采购申请信息判断是否有定标意见申请单
					this.handleShowBidBtn()
					
				}
			})
		},
		// 是否展示中标信息中的按钮
		handleShowBidBtn () {
			if (this.tenderFormData && this.tenderFormData.length && !!this.tenderFormData[0].opinionId) {
				this.isShowBtn = true
			} else {
				this.isShowBtn = false
			}
		},
		// 中标信息
		async getapplyAllListUnit () {
			var params = await {
				column: 'createTime',
				order: 'desc',
				pageNo: 1,
				pageSize: 100,
				billId: this.id
			}
			queryByIdPurchaseCalibrationUnitAllList(params).then(async res => {
				if(res.success){
					this.winBidFormData = res.result || []
				}
			})
		},
		// 获取采购类型
		getProvisionBroadList() {
			const that = this
			that.provisionBroadList = []
			http.get('/api/erp/purchase/material/erpMaterialCategory/queryAllParent').then(res => {
				if (res.success) {
					that.provisionBroadList = res.result
				} else {
					that.$message.warning(res.message)
				}
			})
		},
    validateForm() {
      return this.$refs.form.validate().then(async () => {
        if (!this.tenderFormData.length > 0) {
          this.$u.toast('请添加招标采购申请信息！')
          return Promise.reject('请添加招标采购申请信息！')
        }
        if (!this.winBidFormData.length > 0) {
          this.$u.toast('请添加中标信息！')
          return Promise.reject('请添加中标信息！')
        }
				
				// 当选择了定标意见单时，则不需要做校验
				if (!this.tenderFormData[0].opinionId) {
					// 判断采购类型
					if (this.provisionBroadList && this.provisionBroadList.length > 0) {
						let categoryCode = ''
						this.provisionBroadList.forEach(item => {
							
							if (item.id === this.tenderFormData[0].provisionBroad) {
								categoryCode = item.categoryCode
							}
						})
						var totalBidPrice = new Decimal(0)
						if (this.winBidFormData && this.winBidFormData.length > 0) {
							this.winBidFormData.forEach(item => {
								// 计算中标金额之和
								totalBidPrice = totalBidPrice.add(new Decimal(item.bidding || 0))
							})
						}
						// 采购类型是行政类，中标金额需要超过十万元
						if (categoryCode == '01') {
							if (Number(totalBidPrice) >= 100000) {
								// 小于十万则终止提交
								this.$u.toast('当前中标总金额超过标准金额100000元，请先发起“定标意见单”流程')
								return Promise.reject('当前中标总金额超过标准金额100000元，请先发起“定标意见单”流程')
							}
						} else if (categoryCode == '02') {
							// 采购类型是业务类，中标金额再根据业务分类判断
							if (this.tenderFormData[0].businessSegment == 'HBZXYWBKFZR') {
								// 环保咨询
								if (Number(totalBidPrice) >= 100000) {
									// 小于十万则终止提交
									this.$u.toast('当前中标总金额超过标准金额100000元，请先发起“定标意见单”流程')
									return Promise.reject('当前中标总金额超过标准金额100000元，请先发起“定标意见单”流程')
								}
							} else if (this.tenderFormData[0].businessSegment == 'ZLYWYWBKFZR') {
								// 工程运维
								if (Number(totalBidPrice) >= 200000) {
									// 小于二十万则终止提交
									this.$u.toast('当前中标总金额超过标准金额200000元，请先发起“定标意见单”流程')
									return Promise.reject('当前中标总金额超过标准金额200000元，请先发起“定标意见单”流程')
								}
							} else if (this.tenderFormData[0].businessSegment == 'JYJCYWBKFZR') {
								// 检验检测
								if (Number(totalBidPrice) >= 100000) {
									// 小于十万则终止提交
									this.$u.toast('当前中标总金额超过标准金额100000元，请先发起“定标意见单”流程')
									return Promise.reject('当前中标总金额超过标准金额100000元，请先发起“定标意见单”流程')
								}
							} else if (this.tenderFormData[0].businessSegment == 'SZXXYWBKFZR') {
								// 数字信息
								if (Number(totalBidPrice) >= 200000) {
									// 小于二十万则终止提交
									this.$u.toast('当前中标总金额超过标准金额200000元，请先发起“定标意见单”流程')
									return Promise.reject('当前中标总金额超过标准金额200000元，请先发起“定标意见单”流程')
								}
							} else if (this.tenderFormData[0].businessSegment == 'HBGJYWBKFZR') {
								// 智慧管家
								if (Number(totalBidPrice) >= 100000000) {
									// 小于1000万则终止提交
									this.$u.toast('当前中标总金额超过标准金额100000000元，请先发起“定标意见单”流程')
									return Promise.reject('当前中标总金额超过标准金额100000000元，请先发起“定标意见单”流程')
								}
							} else if (this.tenderFormData[0].businessSegment == 'LTYWYWBKFZR') {
								// 林碳业务
								if (Number(totalBidPrice) >= 100000) {
									// 小于十万则终止提交
									this.$u.toast('当前中标总金额超过标准金额100000元，请先发起“定标意见单”流程')
									return Promise.reject('当前中标总金额超过标准金额100000元，请先发起“定标意见单”流程')
								}
							} else if (this.tenderFormData[0].businessSegment == 'SLYWYWBKFZR') {
								// 水利业务
								if (Number(totalBidPrice) >= 100000000) {
									// 小于1000万则终止提交
									this.$u.toast('当前中标总金额超过标准金额100000000元，请先发起“定标意见单”流程')
									return Promise.reject('当前中标总金额超过标准金额100000000元，请先发起“定标意见单”流程')
								}
							}
						}
					}
				}
				
        return Promise.resolve()
      })
    },
    async onSubmit() {
      await this.validateForm()
			this.isSubmit = true
      try {
        this.loading = true
				var url = ''
				if (this.id) {
					url = edit
				} else {
					url = add
				}
        const response = await url({
          ...this.model,
          detailList: this.tenderFormData,
          unitList: this.winBidFormData,
        })
        this.$u.toast(response.message)
        if (response.success) {
        	var that = this
        	
					// 获取流程列表
					if (this.id) {
						this.getProcessList(this.id)
					} else {
					// 判断添加的时候是否有返回id值
						if (response.result) {
							this.getProcessList(response.result)
						}
					
					}
					this.$refs.uToast.show({
						message: response.message,
						type: 'default',
						complete () {
							// that.isSubmit = false
						}
					})
        }
      } finally {
        // this.loading = false
      }
    },
		
		async onDraft() {
		  // await this.validateForm()
		  this.isSubmit = true
		  try {
		    this.loading = true
		  		var url = ''
		  		if (this.id) {
		  			url = edit
		  		} else {
		  			url = add
		  		}
		    const response = await url({
		      ...this.model,
		      detailList: this.tenderFormData,
		      unitList: this.winBidFormData,
		    })
		    if (response.success) {
					
					this.$refs.uToast.show({
						message: response.message,
						type: 'default',
						complete () {
							this.isSubmit = false
							if (getCurrentPages().length > 1) {
								uni.navigateBack()
							} else {
								uni.reLaunch({
									url: '/pages/home/home'
								})
							}
							
						}
					})
		    }
		  } finally {
		    this.loading = false
		  }
		},
		// 获取流程列表
		getProcessList (id) {
			if (this.isSubmit) {
				this.$refs.processConfig.showPopup = true
				this.$refs.processConfig.formUrl = this.formUrl
				this.$refs.processConfig.formUrlMobile = this.formUrlMobile
				this.$refs.processConfig.flowCode = this.flowCode
				this.$refs.processConfig.edit(id, this.processId, this.beanName)
			}
		},
		// 提交流程成功
		onOk () {
			this.$refs.uToast.show({
				message: '提交成功',
				type: 'success',
				complete () {
					if (getCurrentPages().length > 1) {
						uni.navigateBack()
					} else {
						uni.reLaunch({
							url: '/pages/home/home'
						})
					}
					
				}
			})
		}
  },
  watch: {
    tenderFormData: {
      immediate: true,
      handler(val) {
        if (val?.length) {
          // const total = val.reduce((total, item) => {
          //   return total + item.amount * item.budgetAmount
          // }, 0)
          // this.$set(this.model, 'projectBudget', String(total))
					// this.getPurchasing(val[0].invitationId)
					const promises = val.map((v) => {
						if(!v.projectBudget){
							return erpPurchaseApplyInvitationQueryById({ id:v.invitationId })
						} else {
							return 1
						}
					})
					if(promises.filter(v => v!=1).length){
						Promise.all(promises).then(function (posts) {
							if(posts.length){
								posts.forEach((cv,index) => {
									val[index].projectBudget = cv.result.projectBudget
								})
							}
						})
					}
					let budge = 0
					val.forEach(c => {
						budge += c.projectBudget
					})
					if(this.editCount==0){
						this.editCount = 1
					} else {
						this.$set(this.model, 'budget', budge)
					}
					// this.showAdd = true
					// 当有值的时候判断是否显示新增按钮
					if (val[0].projectId) {
						// 当第一个有projectId,则显示新增按钮
						this.showAdd = false
					} else {
						// 当第一个有projectId,则显示隐藏新增按钮
						this.showAdd = true
					}
        } else {
          this.$set(this.model, 'projectBudget', String(0))
					if(this.editCount==0){
						this.editCount = 1
					} else {
						this.$set(this.model, 'budget', 0)
					}
					this.showAdd = false
        }
      },
    }
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
